<template>
  <div class="equipment">
    <div id="container"></div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import { getequipmentlist, getTitle } from '@/api/echarts';

let map = null;
let distCluster = null;
let pointSimplifierIns = null;

export default {
  name: 'index',
  props: {
    showPoints: {
      type: Boolean,
      default: false,  // 默认不显示点
    },
  },
  data() {
    return {
      lat: null,
      lng: null,
      zoom: 5,  // 地图默认缩放级别
      pointsData: [],  // 存储所有点数据
    };
  },
  mounted() {
    this.initMap();  // 在组件挂载时初始化地图
  },
  watch: {
    // 监听 showPoints 属性的变化，控制点的显示和隐藏
    showPoints(newValue) {
      if (newValue) {
        this.showPointCoordinates();  // 显示点
      } else {
        this.hidePointCoordinates();  // 隐藏点
      }
    }
  },
  methods: {
    // 获取经纬度和缩放信息
    async fetchlnglat() {
      try {
        const title = await getTitle();
        this.lat = parseFloat(title.msg.lat);
        this.lng = parseFloat(title.msg.lng);
        this.zoom = title.msg.zoom;

        // 如果经纬度和缩放值有效，设置地图中心和缩放级别
        if (!isNaN(this.lat) && !isNaN(this.lng) && map) {
          map.setCenter([this.lng, this.lat]);
          map.setZoom(this.zoom);
        } else {
          console.error('无效的经纬度:', this.lat, this.lng, this.zoom);
        }
      } catch (error) {
        console.error('Error fetching title:', error);
      }
    },

    // 初始化地图
    initMap() {
      AMapLoader.load({
        key: "f8c954755588cd09132500151dc4d01c",  // 高德地图 API key
        version: "2.0",
        plugins: ['AMap.Scale', 'AMap.Marker', 'AMap.InfoWindow', 'AMap.MarkerCluster'],
        AMapUI: {
          version: '1.1',
          plugins: ['overlay/SimpleMarker']
        }
      }).then((AMap) => {
        map = new AMap.Map("container", {
          viewMode: "2D",
          terrain: false,
          zoom: this.zoom,
          center: [116.397428, 39.90923],  // 默认中心点
          mapStyle: 'amap://styles/blue',
        });

        // 设置地图的边界，防止地图无限循环移动
        const bounds = new AMap.Bounds(
          new AMap.LngLat(73.502355, 3.837031),  // 西南角
          new AMap.LngLat(135.09567, 53.563624)  // 东北角
        );
        map.setLimitBounds(bounds);

        this.aMapUiLoad();  // 确保地图 UI 组件加载
      }).catch(e => {
        console.log(`高德地图加载错误提示${e}`);
      });
    },

    // 初始化页面上的聚合与点简化功能
    initPage(DistrictCluster, PointSimplifier, utils) {
      pointSimplifierIns = new PointSimplifier({
        map: map,
        autoSetFitView: false,
        zIndex: 110,
        getPosition: function (item) {
          if (!item || !item.lnglat || isNaN(item.lnglat[0]) || isNaN(item.lnglat[1])) {
            return '';
          }
          return item.lnglat;
        },
        getHoverTitle: function (dataItem, idx) {
          return `<div style="height: 12vh;width: 16vw;background-color:#FFFFFF;margin:0;padding:0;z-index:9999999">
            <h2>第${idx + 1}台设备</h2>
            <p>${dataItem.detail}</p>
          </div>`;
        },
        renderOptions: {
          pointStyle: {
            width: 6,
            height: 6,
            fillStyle: 'rgba(153, 0, 153, 0.38)'
          },
          hoverTitleStyle: {
            position: 'top'
          }
        }
      });

      distCluster = new DistrictCluster({
        zIndex: 100,
        map: map,
        autoSetFitView: false,
        getPosition: function (item) {
          if (!item || !item.lnglat || isNaN(item.lnglat[0]) || isNaN(item.lnglat[1])) {
            return null;
          }
          return item.lnglat;
        },
      });

      window.distCluster = distCluster;  // 将 distCluster 暴露到全局变量
    },

    // 加载设备列表数据
    async loadPointsData() {
      try {
        if (this.pointsData.length === 0) {
          const res = await getequipmentlist({ limit: 10000 });
          if (res.code === 0) {
            const data = res.msg;
            this.pointsData = data
              .filter(item => !isNaN(parseFloat(item.lng)) && !isNaN(parseFloat(item.lat)))
              .map(item => ({
                lnglat: [parseFloat(item.lng), parseFloat(item.lat)],
                name: item.name,
                detail: item.detail,
                iSWorkorder: item.iSWorkorder,
                id: item.id,
                mainBind: item.mainBind,
                status: item.status,
                type: item.type,
                count: item.count
              }));
          } else {
            console.error('API 返回错误:', res);
          }
        }
      } catch (error) {
        console.error('请求出错:', error);
      }
    },

    // 显示点坐标
    async showPointCoordinates() {
      await this.loadPointsData();  // 确保数据已加载
      if (pointSimplifierIns && this.pointsData.length > 0) {
        pointSimplifierIns.setData(this.pointsData);
        distCluster.setData(this.pointsData);
      }
    },

    // 隐藏点坐标
    hidePointCoordinates() {
      if (pointSimplifierIns) {
        pointSimplifierIns.setData([]);
        distCluster.setData([]);
      }
    },

    // 加载高德地图的 UI 组件
    aMapUiLoad() {
      AMapUI.load(['ui/geo/DistrictCluster', 'ui/misc/PointSimplifier', 'lib/$', 'lib/utils'], (DistrictCluster, PointSimplifier, $, utils) => {
        this.initPage(DistrictCluster, PointSimplifier, utils);
        this.fetchlnglat();  // 确保地图 UI 组件加载完成后再调用 fetchlnglat
      });
    }
  }
};
</script>

<style lang="scss">
.equipment {
  #container {
    width: 100%;
    height: 120vh;
  }

  .amap-ui-district-cluster-region {
    background-color: rgba(192,192,192,0.5) !important;
  }
}
</style>
